package v1

import (
	"github.com/gin-gonic/gin"
	"ota/bll"
	"ota/model"
	"ota/server/web/middleware"
	"ota/utils"
)

var FirmwareType = &firmwareType{}

func init() {
	RegisterRouter(FirmwareType)
}

type firmwareType struct{}

// Init
func (a *firmwareType) Init(r *gin.RouterGroup) {
	g := r.Group("/firmwareType", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}
}

/*
类型名称：必填项，且不允许重复，字段不超过15个字符
类型描述：不超过50个字符
*/
// create
func (a *firmwareType) create(c *gin.Context) {
	var (
		in  = &model.FirmwareTypeCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.FirmwareType.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update
func (a *firmwareType) update(c *gin.Context) {
	var (
		in  = &model.FirmwareTypeUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.FirmwareType.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list
func (a *firmwareType) list(c *gin.Context) {
	var (
		in  = &model.FirmwareTypeListRequest{}
		out = &model.FirmwareTypeListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.FirmwareType.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// list
func (a *firmwareType) find(c *gin.Context) {
	var (
		in  = &model.FirmwareTypeInfoRequest{}
		out = &model.FirmwareTypeInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.FirmwareType.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

/*
删除：已有数据关联该固件类型，不允许删除
点击删除按钮，报错提示：“已有数据关联该固件类型，不允许删除”
如没有数据关联，支持删除
*/
// delete
func (a *firmwareType) delete(c *gin.Context) {
	var (
		in  = &model.FirmwareTypeDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.FirmwareType.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
